//
//  BVRecevicedAddressViewController.m
//  BuyVegetables
//
//  Created by 叶思超 on 15/10/13.
//  Copyright (c) 2015年 叶思超. All rights reserved.
//

#import "BVRecevicedAddressViewController.h"
#import "BVConst.h"
#import "BVAddAddressViewController.h"
#import "BVModifyAddressViewController.h"
#import "HttpTool.h"
#import "BVReceviceAddress.h"
#import "MJExtension.h"
#import "BVCorrectOrderViewController.h"
#import "BVReceviceAddressCell.h"

@interface BVRecevicedAddressViewController () <UITableViewDataSource, UITableViewDelegate, BVAddAddressViewControllerDelegate, BVModifyAddressViewControllerDelegate>
/**
 *  创建tableView
 */
@property (nonatomic, strong) UITableView *tableView;
/**
 *  存放所有地址信息
 */
@property (nonatomic, strong) NSMutableArray *addressArray;
@end

@implementation BVRecevicedAddressViewController

- (NSMutableArray *)addressArray {
    if (!_addressArray) {
        _addressArray = [NSMutableArray array];
    }
    return _addressArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置导航栏
    [self setupNav];
    // 获取地址信息
    [self loadAddress];
    
    // 创建tableView
    [self setupTableView];
    
}
#pragma mark -- 获取地址信息
- (void)loadAddress {
    // 拼接路径
    NSString *url = [NSString stringWithFormat:@"%@/VegetableUserAPI/getUserAddressListByUid", Path];
    
    // 拼接参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *userinfo = [defaults dictionaryForKey:@"USERINFO"];
    NSString *user_id = userinfo[@"id"];
    if (user_id != nil) {
        params[@"user_id"] = user_id;
        
        [HttpTool get:url params:params success:^(id responseObj) {

                BVLog(@"获取地址列表成功-----%@", responseObj);
                // 清空数组
                [self.addressArray removeAllObjects];

                NSArray *array = [BVReceviceAddress objectArrayWithKeyValuesArray:responseObj[@"data"]];
                
                [self.addressArray addObjectsFromArray:array];
                // 刷新tableview
                
                [self.tableView reloadData];
        } failure:^(NSError *error) {
            BVLog(@"请求失败-----%@", error);
        }];
    } else  {
        
    }
}

#pragma mark -- 创建tableview
- (void)setupTableView {
    self.tableView = [[UITableView alloc] init];
    [self.view addSubview:self.tableView];
    self.tableView.frame = CGRectMake(0, 64, BVScreenW, BVScreenH - 64 );
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[BVReceviceAddressCell class] forCellReuseIdentifier:@"iden"];
    
    // 新增地址
    UIView *addAddressView = [[UIView alloc] init];
    addAddressView.frame = CGRectMake(0, BVScreenH - 60, BVScreenW, 60);
    addAddressView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:addAddressView];
    
    UIButton *addAddressButton = [[UIButton alloc] init];
    addAddressButton.frame = CGRectMake(10, 10, BVScreenW - 2 * 10, 40);
    addAddressButton.backgroundColor = BVBaseOrangeColor;
    [addAddressButton setTitle:@"新增地址" forState:UIControlStateNormal];
    [addAddressButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    addAddressButton.titleLabel.font = [UIFont systemFontOfSize:20];
    addAddressButton.layer.borderColor = [UIColor whiteColor].CGColor;
    addAddressButton.layer.borderWidth = 1;
    addAddressButton.layer.masksToBounds = YES;
    addAddressButton.layer.cornerRadius = 3;
    [addAddressButton addTarget:self action:@selector(addAddressClick) forControlEvents:UIControlEventTouchUpInside];
    [addAddressView addSubview:addAddressButton];
    
    
}

#pragma mark -- UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //直接计算
    return [self cellHeightForIndexPath:indexPath cellContentViewWidth:BVScreenW tableView:self.tableView];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  self.addressArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    BVReceviceAddress * address = self.addressArray[indexPath.row];
    
    BVReceviceAddressCell * cell = [tableView dequeueReusableCellWithIdentifier:@"iden"];
    
    cell.nameLabel.text = address.contact;
    cell.telLabel.text = address.mobile;
    cell.addressLabel.text = [NSString stringWithFormat:@"%@  %@", address.receive_address, address.detailed_address];
    cell.businessLabelC.text = address.business_circle;
    
    cell.modifyAddresButton.tag = indexPath.row;
    [cell.modifyAddresButton addTarget:self action:@selector(modifyAddresButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}

#pragma mark -- UITableviewDelegate
/**
 *  删除某行
 */
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // 删除某行
        [self deleteRow:indexPath.row];
        // 删除指定行
        if (indexPath.row < self.addressArray.count) {
            [self.addressArray removeObjectAtIndex:indexPath.row];
        }
        // 刷新数据
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.delegate respondsToSelector:@selector(recevicedAddressDidFinish:addrss:)]) {
        [self.delegate recevicedAddressDidFinish:self addrss:self.addressArray[indexPath.row]];
        ROOTNAVPOP
    }
}

#pragma mark -- 删除某行
- (void)deleteRow:(NSUInteger)row {
    // 拼接路径
    NSString *url = [NSString stringWithFormat:@"%@/VegetableUserAPI/doDeleteUserAddressById", Path];
    
    // 拼接参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    BVReceviceAddress *receviceAddress = self.addressArray[row];
    params[@"address_id"] = receviceAddress.ID;
    
    [HttpTool get:url params:params success:^(id responseObj) {
        if ([responseObj[@"code"] isEqualToString:@"1"]) {
            BVLog(@"删除地址成功----%@", responseObj);
        } else {
            BVLog(@"删除地址失败----%@", responseObj);
        }
    } failure:^(NSError *error) {
        BVLog(@"请求失败-----%@", error);
    }];
}

#pragma mark -- button点击事件
/**
 *  修改地址
 */
- (void)modifyAddresButtonClick:(UIButton *)button {
    
    BVModifyAddressViewController *modifyAddressVC = [[BVModifyAddressViewController alloc] init];
    modifyAddressVC.delegate = self;
    modifyAddressVC.receviceAddress = self.addressArray[button.tag];
    ROOTNAVPUSH(modifyAddressVC, YES);
}

/**
 *  添加新地址
 */
- (void)addAddressClick {
    
    BVAddAddressViewController *addAddressVC = [[BVAddAddressViewController alloc] init];
    addAddressVC.delegate = self;
    ROOTNAVPUSH(addAddressVC, YES);
}

#pragma mark -- BVModifyAddressViewControllerDelegate 
- (void)modifyAddressDdiFinish:(BVModifyAddressViewController *)modifyAddress {
    
    // 加载数据
    [self loadAddress];
}

#pragma mark -- BVAddAddressViewControllerDelegate
- (void)addAddressDidFinish:(BVAddAddressViewController *)addAddress {

    // 刷新数据
    [self loadAddress];
}

#pragma mark -- 设置导航栏
- (void)setupNav {
    if (self.isLeftMenu) {
        self.navigationItem.title = @"我的地址";
    } else {
        self.navigationItem.title = @"选择收货地址";
    }
    self.navigationController.navigationBar.barTintColor = BVBaseOrangeColor;
    self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(backClick)];
}

#pragma mark -- 返回
- (void)backClick {

    ROOTNAVPOP;
}
@end
